package net.jsoft.platform.core.util.platform;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;

public class PlatformUtils
{
    //    private static SimpleDateFormat sdf = new SimpleDateFormat();

    private static String COMMON_DATE = "yyyy-MM-dd";

    public static String createPK()
    {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getRealPath(String subPath)
    {
        URL url = Thread.currentThread().getContextClassLoader().getResource("");
        String path = null;
        path = url.toString() + subPath;
        if (path.startsWith("file:/"))
        {
            path = path.substring(6);
        }
        return path;
    }

    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath)
    {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    // @描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath)
    {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /**
     * 验证EXCEL文件
     * 
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath)
    {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath)))
        {
            return false;
        }
        return true;
    }

    /**
     * 获取两个日期之间的日期
     * 
     * @param start
     *            开始日期
     * @param end
     *            结束日期
     * @return 日期集合
     */
    public static List<Date> getBetweenDates(Date start, Date end)
    {
        List<Date> result = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd))
        {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }

    public static long getWeeks(Date start, Date end)
    {
        return (end.getTime() - start.getTime()) / (1000 * 3600 * 24 * 7);
    }

    public static Date getDayByadd(Date start, int i)
    {
        Calendar date = Calendar.getInstance();
        date.setTime(start);
        date.set(Calendar.DATE, date.get(Calendar.DATE) + i);
        return date.getTime();
    }

    public static Date getdate(String baseVersionDateStr) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE);
        return sdf.parse(baseVersionDateStr);
    }

    public static Date formateDate(String baseVersionDateStr, String patten) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat(patten);
        return sdf.parse(baseVersionDateStr);
    }

    public static String getdate(Date baseVersionDateStr) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE);
        return sdf.format(baseVersionDateStr);
    }

    public static String formateDate(Date baseVersionDateStr, String patten) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat(patten);
        return sdf.format(baseVersionDateStr);
    }

    // JAVA获取某段时间内的所有日期
    public static List<Date> findDates(Date dBegin, Date dEnd)
    {
        List<Date> lDate = new ArrayList<Date>();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime()))
        {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

    public static Map<String, Date> getDays(Date date)
    {
        if (date == null)
        {
            date = new Date();
        }
        Map<String, Date> map = new HashMap<String, Date>();
        Calendar cal = Calendar.getInstance();
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat(COMMON_DATE);
            cal.setTime(sdf.parse(sdf.format(date)));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        map.put("today", cal.getTime());

        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek)
        {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        map.put("thisWeekMonday", cal.getTime());
        cal.add(Calendar.DATE, -7); // 上星期一
        map.put("lastWeekMonday", cal.getTime());
        cal.add(Calendar.DATE, 14); // 下星期一
        map.put("nextWeekMonday", cal.getTime());
        cal.add(Calendar.DATE, 6); // 下星期日
        map.put("nextWeekSunday", cal.getTime());
        cal.add(Calendar.DATE, -7); // 本星期日
        map.put("thisWeekSunday", cal.getTime());
        cal.add(Calendar.DATE, -7); // 上星期日
        map.put("lastWeekSunday", cal.getTime());
        return map;
    }

    public static String formattedOutputDecimal(double decimal)
    {
        DecimalFormat df = new DecimalFormat("######0.00");
        String result = df.format(decimal);
        return result;
    }

    public static String formattedDecimalToPercentage(double decimal)
    {
        //获取格式化对象  
        NumberFormat nt = NumberFormat.getPercentInstance();
        //设置百分数精确度2即保留两位小数  
        nt.setMinimumFractionDigits(2);
        return nt.format(decimal);
    }

    public static List<String> getAllDate(String start, String end) throws ParseException
    {
        Date lastWeekMondayD = getdate(start);
        Date nextWeekSundayD = getdate(end);
        return getAllDate(lastWeekMondayD, nextWeekSundayD);

    }

    public static List<String> getAllDate(Date start, Date end)
    {
        List<String> list = new ArrayList<String>();
        try
        {
            Date lastWeekMondayD = start;
            Date nextWeekSundayD = end;
            if (lastWeekMondayD.compareTo(nextWeekSundayD) > 0)
            {
                return list;
            }
            Calendar lD = Calendar.getInstance();
            lD.setTime(lastWeekMondayD);

            Calendar nD = Calendar.getInstance();
            nD.setTime(nextWeekSundayD);
            while (true)
            {
                if (lD.after(nD))
                {
                    break;
                }
                list.add(getdate(lD.getTime()));
                lD.add(Calendar.DATE, 1);
            }
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return list;

    }

    public static final byte[] compress(String paramString)
    {
        if (paramString == null)
            return null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        byte[] arrayOfByte;
        try
        {
            byteArrayOutputStream = new ByteArrayOutputStream();
            zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
            zipOutputStream.putNextEntry(new ZipEntry("0"));
            zipOutputStream.write(paramString.getBytes());
            zipOutputStream.closeEntry();
            arrayOfByte = byteArrayOutputStream.toByteArray();
        }
        catch (IOException localIOException5)
        {
            arrayOfByte = null;
        }
        finally
        {
            if (zipOutputStream != null)
                try
                {
                    zipOutputStream.close();
                }
                catch (IOException localIOException6)
                {
                }
            if (byteArrayOutputStream != null)
                try
                {
                    byteArrayOutputStream.close();
                }
                catch (IOException localIOException7)
                {
                }
        }
        return arrayOfByte;
    }

    @SuppressWarnings("unused")
    public static final String decompress(byte[] paramArrayOfByte)
    {
        if (paramArrayOfByte == null)
            return null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        ZipInputStream zipInputStream = null;
        String str;
        try
        {
            byteArrayOutputStream = new ByteArrayOutputStream();
            byteArrayInputStream = new ByteArrayInputStream(paramArrayOfByte);
            zipInputStream = new ZipInputStream(byteArrayInputStream);
            ZipEntry localZipEntry = zipInputStream.getNextEntry();
            byte[] arrayOfByte = new byte[1024];
            int i = -1;
            while ((i = zipInputStream.read(arrayOfByte)) != -1)
                byteArrayOutputStream.write(arrayOfByte, 0, i);
            str = byteArrayOutputStream.toString();
        }
        catch (IOException localIOException7)
        {
            str = null;
        }
        finally
        {
            if (zipInputStream != null)
                try
                {
                    zipInputStream.close();
                }
                catch (IOException localIOException8)
                {
                }
            if (byteArrayInputStream != null)
                try
                {
                    byteArrayInputStream.close();
                }
                catch (IOException localIOException9)
                {
                }
            if (byteArrayOutputStream != null)
                try
                {
                    byteArrayOutputStream.close();
                }
                catch (IOException localIOException10)
                {
                }
        }
        return str;
    }

    public static Date getSysDate()
    {
        return new Date();
    }

    public static String getSysDateStr() throws ParseException
    {
        return getdate(getSysDate());
    }

    /** 
     * 对象转数组 
     * @param obj 
     * @return 
     */
    public static byte[] toByteArray(Object obj)
    {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return bytes;
    }

    /** 
     * 数组转对象 
     * @param bytes 
     * @return 
     */
    public static Object toObject(byte[] bytes)
    {
        Object obj = null;
        try
        {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
        }
        return obj;
    }

    public static String getIpAddr(HttpServletRequest request)
    {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}